package james.gan.common;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExtensionLoader {

	private static final Logger logger = LoggerFactory.getLogger(ExtensionLoader.class);

	public static <T> List<T> load(Class<T> factoryClass, ClassLoader classLoader) {
		Assert.assertNotNull("'factoryClass' must not be null", factoryClass);

		ClassLoader classLoaderToUse = classLoader;
		if (classLoaderToUse == null) {
			classLoaderToUse = ExtensionLoader.class.getClassLoader();
		}
		ServiceLoader<T> load = ServiceLoader.load(factoryClass, classLoaderToUse);
		List<T> result = new ArrayList<T>();
		for (Iterator<T> iterator = load.iterator(); iterator.hasNext();) {
			T next = iterator.next();
			result.add(next);
		}
		logger.debug("load[{}],size[{}],details[{}]", factoryClass, result.size(),result);
		return result;
	}
	

}
